﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;

namespace LetiLib.Utils
{
    class JSONHelper
    {
        public static T Deserialise<T>(string json) where T : class
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
                obj = serialiser.ReadObject(ms) as T;
            }

            return obj;
        }

        public static string Serialise<T>(T entity) where T : class
        {
            string strResult = string.Empty;
            DataContractJsonSerializer serialiser = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream ms = new MemoryStream())
            {
                serialiser.WriteObject(ms, entity);
                ms.Position = 0;
                using (StreamReader reader = new StreamReader(ms))
                {
                    strResult = reader.ReadToEnd();
                }
            }

            return strResult;
        }
    }
}
